import requests
import pytest
from loguru import logger
from conf.env import get_env_info
import datetime

class BaseApi(object):
    headers = {}
    method = ""
    url = ""
    data = {}
    json = {}
    files = {}
    proxies = {'http': 'http://localhost:8888', 'https': 'http://localhost:8888'}

    # def set_headers(self, headers):
    #     self.headers = headers
    #     return self

    def set_data(self, data):
        self.data = data
        return self

    def set_json(self, json):
        self.json = json
        return self

    def set_headers(self, headers):
        self.headers = headers
        return self

    def set_files(self, files):
        self.files = files
        return self

    def set_url(self, url):
        self.url = url
        return self

    def run(self, session=None):
        session = session or requests.sessions.Session()
        print()
        self.response = session.request(method=self.method,
                                        url=self.url,
                                        headers=self.headers,
                                        json=self.json,
                                        data=self.data,
                                        files=self.files,
                                        # proxies=self.proxies,
                                        verify=False
                                        )
        return self

    def assume(self, realistic, exception):
        pytest.assume(realistic == exception)
        return self

    def extract(self, field):  # 对返回数据的提取
        value = self.response
        for _key in field.split('.'):
            # print("_key========", _key)
            if isinstance(value, requests.Response):
                if _key in ["json()", "json"]:  # 转换成json取值
                    value = self.response.json()
                else:
                    value = getattr(value, _key)

                # print("response_value=========", value)
            elif isinstance(value, (requests.structures.CaseInsensitiveDict, dict)):
                # print("structures_value========", value)
                value = value[_key]
            elif isinstance(value, list):
                _key = int(_key)
                # print("list_value=========", value)
                value = value[_key]
        return value

    def validate(self, key, except_value):
        value = self.extract(key) # 提取返回部分数据
        pytest.assume(value == except_value)
        return self

    def get_response(self):
        return self.response



class Cui(BaseApi):
    host = get_env_info("icp.host")

    def set_url(self):
        self.url = "https://" + self.host + self.url + self.suffix
        # print("请求的url为", self.url)
        return self


class Yuncheng(BaseApi):
    host = get_env_info("yuncheng.host")

    def set_url(self):
        self.url = "http://" + self.host + self.url + self.suffix
        # print("=======url============", self.url)
        return self


